<template>
  <el-drawer v-model="drawerVisible" size="60%" :title="props.title" :show-close="true" @closed="closeDrawer">
    <template #default>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-if="!readonly" type="primary" plain icon="Plus" @click="handleFile">上传文件</el-button>
        </el-col>
        <right-toolbar :show-search="true" @query-table="loadFileList"></right-toolbar>
      </el-row>

      <el-table v-if="true" v-loading="loading" :data="ossList" border>
        <el-table-column type="index" width="55" align="center" label="序号" :index="rowIndex" />
        <el-table-column label="文件名" align="center" prop="originalName" />
        <el-table-column label="后缀" align="center" prop="fileSuffix" width="80" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="createByName" width="150" />
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" text plain size="small" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
            <el-button type="danger" text plain size="small" icon="Delete" @click="handleDelete(scope.row)" v-if="!readonly">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="loadFileList"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="closeDrawer" plain type="primary">关闭</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 添加或修改OSS对象存储对话框 -->

  <fileUpload
    v-model="dialog.visible"
    :resource-ids="props.resourceIds"
    :type-flag="props.typeFlag"
    :limit="props.uploadLimit"
    :file-size="props.uploadFileSize"
    :file-type="props.uploadFileType"
    :show-tip="props.uploadShowTip"
    @close="closeFileUpload"
  />
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes';
import { delOss, listByResourceIdsAndTypeFlag } from '@/api/system/oss';
import { OssVO } from '@/api/system/oss/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue', 'close']);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: () => false
  },
  title: propTypes.string.def(''),
  resourceIds: {
    type: [Array],
    default: () => []
  },
  visible: propTypes.bool.def(false),
  typeFlag: propTypes.string.def(),
  // 文件上传的相关配置
  // 数量限制
  uploadLimit: propTypes.number.def(5),
  // 大小限制(MB)
  uploadFileSize: propTypes.number.def(30),
  // 文件类型, 例如 ['ppt', 'pptx', 'xls', 'xlsx', 'doc', 'docx', 'txt', 'md', 'pdf', 'zip', 'rar', '7z', 'png', 'jpg', 'jpeg', 'bmp']
  uploadFileType: propTypes.array.def([]),
  // 是否显示提示
  uploadShowTip: propTypes.bool.def(true),
  //只能查看
  readonly: propTypes.bool.def(false)
});

const initFormData = {
  file: undefined
};

const form = ref({ ...initFormData });

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/** 文件按钮操作 */
const handleFile = () => {
  reset();
  dialog.visible = true;
  dialog.title = '上传文件';
};
/** 确认按钮 */
const ok = () => {
  dialog.visible = false;
  loadFileList();
  reset();
};
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};
/** 表单重置 */
function reset() {
  form.value = { ...initFormData };
}

const loading = ref(true);
const ossList = ref<OssVO[]>([]);
const total = ref(0);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderByColumn: 'createTime',
  isAsc: 'asc'
});

const drawerVisible = ref(props.modelValue);
// 行索引
const rowIndex = (index: number) => {
  return (queryParams.pageNum - 1) * queryParams.pageSize + (index + 1);
};

const closeDrawer = () => {
  proxy.$nextTick(() => {
    total.value = 0;
    emit('update:modelValue', false);
    reset();
  });
};
// 监听父组件visible属性变化
watch(
  () => props.modelValue,
  (val) => {
    drawerVisible.value = val;
    if (val) {
      loadFileList();
    }
  }
);
// 监听父组件resourceIds属性变化
/*watch(
  () => props.resourceIds,
  (val) => {
    // console.log('resourceIds 变化：', val);
  }
);*/

/** 关闭文件上传对话框 */
const closeFileUpload = (fileList: OssVO[]) => {
  loadFileList();
  emit('close', fileList);
};

const loadFileList = async () => {
  if (props.resourceIds && props.resourceIds.length > 0) {
    const params = {
      ...queryParams,
      typeFlag: props.typeFlag,
      resourceIds: props.resourceIds.join(',')
    };
    const res = await listByResourceIdsAndTypeFlag(params);
    ossList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }
};

/** 下载按钮操作 */
const handleDownload = (row: OssVO) => {
  proxy?.$download.oss(row.ossId);
};
/** 删除按钮操作 */
const handleDelete = async (row?: OssVO) => {
  const ossIds = row?.ossId;
  await proxy?.$modal.confirm('是否确认删除文件: "' + row.originalName + '"?');
  loading.value = true;
  await delOss(ossIds).finally(() => (loading.value = false));
  await loadFileList();
  proxy?.$modal.msgSuccess('删除成功');
};
</script>

<style lang="scss" scoped></style>
